/**
 * 服务
 * */
package org.zmhhxl.sample3.oauth2.a.service;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.zmhhxl.sample3.oauth2.a.authentications.model.CustomOAuth2User;
import org.zmhhxl.sample3.oauth2.a.authentications.strategy.context.Oauth2UserConverterContext;

/**
 * @author twelvet
 * @WebSite www.twelvet.cn
 * @Description: 自定义获取第三方code换信息,自定义三方oauth2登录获取用户信息服务
 */
@Service
   //@Component
   @Slf4j
public class CustomOAuth2UserService extends DefaultOAuth2UserService  {

   private final Oauth2UserConverterContext userConverterContext;
   private final IOauth2ThirdAccountService thirdAccountService;

   public CustomOAuth2UserService(Oauth2UserConverterContext userConverterContext, IOauth2ThirdAccountService thirdAccountService) {
      super();
      this.userConverterContext = userConverterContext;
      this.thirdAccountService = thirdAccountService;
   }

   @Override
   public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
      Assert.notNull(userRequest, "userRequest cannot be null");
      try {
         OAuth2User oAuth2User = super.loadUser(userRequest);
         if(oAuth2User instanceof CustomOAuth2User){
            log.info("直接返回用户信息：{}",oAuth2User);
         }else{
            log.info("第三方登录成功first,直接返回用户信息：{}",oAuth2User);
         }
         // 转为项目中的三方用户信息
         CustomOAuth2User customOAuth2User = userConverterContext.convert(userRequest, oAuth2User);

         // 添加完善其他信息...

         // 检查用户信息,在后面登录成功的地方处理保存
         //ThirdPartyUser thirdPartyUser = thirdAccountService.checkAndSaveUser(customOAuth2User);

         // 添加完善其他信息...

         return customOAuth2User;
      }catch (Exception e){
         // 获取当前request
         RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
         if (requestAttributes == null) {
            throw new AuthenticationServiceException("Failed to get the current request.");
         }
         HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
         // 将异常放入session中
         request.getSession(Boolean.FALSE).setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, e);
         throw new AuthenticationServiceException(e.getMessage(), e);
      }

   }
}

//
//      // 第三方ID(可以通过此ID获取自定义授权方式)
//      String registrationId = userRequest.getClientRegistration().getRegistrationId();
//      String name = (String) oAuth2User.getAttribute("name");
//      log.info("直接返回用户信息1,此处优先于LoginSuccessHandler及oauth2UserHandler：sssss {}; {} || {}", name,userRequest.getClientRegistration(),oAuth2User);
//
//      // Extract the attributes from the OAuth2User
//      if (name == null) {
//         name = "Unknown User";
//      }
//
//      //添加权限
//      // 这里你可以根据需要添加权限
//      //Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER_zmhhxl"));
//      // 创建一个新的权限
//      GrantedAuthority newAuthority = new SimpleGrantedAuthority("ROLE_USERz");  //.map(GrantedAuthority::getAuthority)
//
//      Set<String> authorities1 =oAuth2User.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
//
//      authorities1.add("zmhhxl_role");
//
//      Collection<GrantedAuthority> authorities = authorities1.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
//
//      // 查询或创建本地用户
////      Optional<UserInfo> localUser = userRepository.findByUsername(name);
////      if (localUser.isPresent()){
////             log.info("用户已存在，直接返回用户信息：{}",localUser.get());
////
////             // 返回新的
////         return new DefaultOAuth2User(localUser.get().getAuthorities(), oAuth2User.getAttributes(), "id");
////      }
////         localUser = userRepository.findByUsername(name))
////            .orElseGet(() -> userRepository.createUser(provider, email, name));
//      log.info("直接返回用户信息2：sssss {} ", oAuth2User);
//      // Create a new OAuth2User with the modified attributes
//      //return new DefaultOAuth2User(oAuth2User.getAuthorities(), oAuth2User.getAttributes(), "name");
//
//      return new CustomOAuth2User(oAuth2User, "authorities");
//      //return oAuth2User;
//
//
////      OAuth2UserService oAuth2UserService = userServiceMap.get(registrationId);
////
////      if (oAuth2UserService != null) {
////         // 采用默认换取方式
////         oAuth2UserService = (OAuth2UserService<R, U>) defaultOAuth2UserService;
////         //oAuth2UserService.loadUser((R)userRequest);
////         log.info("第三方登录方式 ccccc ======：{} || {}", registrationId,oAuth2UserService.loadUser((R)userRequest));
////      }else{
////         oAuth2UserService = (OAuth2UserService<R, U>) defaultOAuth2UserService;
////      }
////
////      return oAuth2UserService.loadUser((R) userRequest);
//
//
//      // 获取第三方登录信息
//      //Map<String, Object> attributes = oAuth2User.getAttributes();
//
//      // 根据第三方ID查找或创建用户
////      String providerUserId = (String) attributes.get("sub");
////      User user = userRepository.findByName(providerUserId);
////
////      if (user == null) {
////         // 创建新用户
////         user = new User();
////         user.setProviderUserId(providerUserId);
////         // 设置其他用户信息...
////         userRepository.save(user);
////      }
//
////      return new DefaultOAuth2User(
////            Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
////            attributes,
////            "sub"
////      );

/**
 * 默认的获取方式，适配大部分第三方
 */
//   public CustomOAuth2UserService() {
//      super();
//   }

/**
 * 自定义换取方式
 */
// private final Map<String, OAuth2UserService> userServiceMap;

//   public CustomOAuth2UserService(Map<String, OAuth2UserService> userServiceMap) {
//      //this.userServiceMap = Collections.unmodifiableMap(userServiceMap);
//   }

//   @Autowired
//private OAuth2UserRepositoryHandler.UserRepository userRepository;
//   @Autowired
//   private UserInfoRepository userRepository;

